var app = getApp()
var modal = require('../../utils/modal');
var request = require('../../utils/request');
var utils = require('../../utils/utils');
var comment = require('../widget/comment/comment');
var addrPicker = require('../../components/addrPicker/addrPicker');
var goTop = require('../widget/goTop/goTop');
var pay = require('../../common/wxpay');

var pageSetting = {
  callback: function (componentName) {
    switch (componentName) {
      case 'addrPicker':
        //选择地址之后的回调函数
        if (this.data.address.id != arguments[1].id) {
          var setData = {};
          setData.address = this.data.address = arguments[1];
          this.freshFee(setData);
        }
        break;
      default:
        break;
    }
  },
  data: {
    showPage: 0,
    subsIndex: 0,//当前物流
    shippingFee: 0,
    shippingFeeText: '',
    shippingFreeFeeText: '',
    totalAmountText: '',
    shippinpLayerShow: 0,//显示选择物流弹窗
    gongyiLayerShow: 1,
    address: { //当前收货地址
      id: '-1',
      final_address: '添加收货地址'
    },
    submiting: 0
    //id skuId num

  },
  onLoad: function (option) {
    var setData = {};
    setData.id = this.data.id = option.id;
    setData.skuId = this.data.skuId = option.sku_id;
    setData.num = this.data.num = parseInt(option.num);
    setData.showPage = this.data.showPage = 1;
    this.loadData(setData);
  },
  onShow: function () {
    this.data.submiting = 0;
  },
  loadData: function (setData) {
    var that = this;
    var option = {
      "zp:zc_api:act:sub":
      {
        "id": that.data.id,
        "sku_id": that.data.skuId,
        "num": that.data.num,
      }
    };
    modal.loading();
    //获取订单信息
    request.post({
      path: '/wxapp_api/api'
    }, option).then(function (res) {
      modal.hide();
      if (res['zp:zc_api:act:sub'].ret == 0) {
        var respData = res['zp:zc_api:act:sub'].data;
        setData.sku = that.data.sku = respData.sku;
        for (var i = 0; i < respData.subs.length; i++) {
          if (respData.subs[i].default) {
            respData.subs[i].default = JSON.parse(respData.subs[i].default);
          }
          if (respData.subs[i].designated_postage) {
            respData.subs[i].designated_postage = JSON.parse(respData.subs[i].designated_postage);
          }
          if (respData.subs[i].free_postage) {
            respData.subs[i].free_postage = JSON.parse(respData.subs[i].free_postage);
          }
        }
        setData.subs = that.data.subs = respData.subs;
        /*获取默认地址*/
        that.wiiAddrPickerGetDefaultAddr({ 'wiiAddrPickerUseWxAddr': true }, function (res) {
          setData.address = that.data.address = res;
          that.freshFee(setData);
        });
      } else {
        modal.toast(res['zp:zc_api:act:sub']['msg']);
      }
    });
  },
  reduceNum: function () {
    if (this.data.num > 1) {
      this.data.num -= 1;
      this.freshFee({
        num: this.data.num
      });
    }
  },
  increaseNum: function () {
    if (this.data.num < this.data.sku.inventory) {
      this.data.num += 1;
      this.freshFee({
        num: this.data.num
      });
    }
  },
  inputNum: function (ev) {
    var targetVal = parseInt(ev.detail.value);
    if (isNaN(targetVal) || targetVal < 1) {
      targetVal = 1;
    }
    if (targetVal > parseInt(this.data.sku.inventory)) {
      targetVal = parseInt(this.data.sku.inventory);
    }
    if (this.data.num != targetVal) {
      this.data.num = targetVal;
      this.freshFee({ num: this.data.num });
    }
  },
  shippinpLayerShow: function () {
    if (this.data.subs.length > 1) {
      this.data.shippinpLayerShow = 1;
      this.setData({
        shippinpLayerShow: this.data.shippinpLayerShow
      });
    }
  },
  pickShippintMethod: function (ev) {
    var setData = {};
    setData.shippinpLayerShow = this.data.shippinpLayerShow = 0;
    if (this.data.subsIndex != ev.currentTarget.dataset.index) {
      setData.subsIndex = this.data.subsIndex = ev.currentTarget.dataset.index;
      this.freshFee(setData);
    } else {
      this.setData(setData);
    }
  },
  colseLayer: function () {
    this.data.shippinpLayerShow = 0;
    this.setData({
      shippinpLayerShow: this.data.shippinpLayerShow
    });
  },
  submitOrder: function () {
    var that = this;
    if (that.data.address.id != undefined && that.data.address.id > 0) {
      if (that.data.submiting == 0) {
        that.data.submiting = 1;
        var option = {
          "zp:zc_api:order:submit": {
            "act_id": that.data.id,
            "sku_id": that.data.skuId,
            "trans_id": that.data.subs[that.data.subsIndex].id,
            "address_id": that.data.address.id,
            "province_id": that.data.address.province_id,
            "province": that.data.address.province_name,
            "city_id": that.data.address.city_id,
            "city": that.data.address.city_name,
            "area_id": that.data.address.area_id,
            "area": that.data.address.area,
            "address": that.data.address.addr,
            "name": that.data.real_name,
            "phone": that.data.address.mobile,
            "purchase_count": that.data.num
          }
        };
        modal.loading();
        request.post({
          path: '/wxapp_api/api'
        }, option).then(function (res) {
          that.data.submiting = 0;
          modal.hide();
          if (res['zp:zc_api:order:submit'].ret == 0) {
            var respData = res['zp:zc_api:order:submit'].data;
            // wx.navigateTo({
            //   url: '../submit/submit?order_id=' + respData.parent_order
            // })
            pay.callwxPay(respData.parent_order)
          } else {
            modal.toast(res['zp:zc_api:order:submit']['msg']);
          }
        });
      }
    } else {
      modal.toast('请填写收货地址');
    }
  },
  //计算运费
  calculateFreight: function () {
    var that = this;
    if (that.data.subs.length > 0) {
      var postageRule = that.data.subs[that.data.subsIndex];//选择的物流规则      
      var cityId = that.data.address.city_id == undefined ? 0 : that.data.address.city_id;
      var goodsNum = that.data.num;
      var goodsTotalAmount = that.data.sku.price * goodsNum;//商品总价 单位份
      if (postageRule.type == 0) {
        return 0;
      } else {
        var sign = false;//是否已经计算出结果
        //检查满邮
        if (postageRule.is_free == 1) {
          for (var i = 0; i < postageRule.free_postage.length; i++) {
            //地区                             
            for (var provinceId in postageRule.free_postage[i].ids) {
              //provinceId == 0 为全国
              if (provinceId == 0 || (cityId != 0 && postageRule.free_postage[i].ids[provinceId].indexOf(String(cityId)) != -1)) {
                if (goodsTotalAmount >= postageRule.free_postage[i].postage * 100) {//条件
                  return 0;
                  sign = true;
                } else {
                  that.data.shippingFreeFeeText = '（满' + postageRule.free_postage[i].postage + '元包邮）';
                }
                break;
              }
            }

            if (sign == true) {
              break;
            }
          }
        }
        //检查指定地区
        if (cityId != 0 && !sign && postageRule.designated_postage && postageRule.designated_postage.length > 0) {//检查特殊地区
          for (var j = 0; j < postageRule.designated_postage.length; j++) {
            for (var pId in postageRule.designated_postage[j].ids) {
              if (pId == 0 || postageRule.designated_postage[j].ids[pId].indexOf(String(cityId)) != -1) {
                var ptRule = postageRule.designated_postage[j].postage;
                return ptRule.begin_postage * 100 + (goodsNum - ptRule.begin > 0 ? Math.ceil((goodsNum - ptRule.begin) / ptRule.add) : 0) * ptRule.add_postage * 100;
                sign = true;
                break;
              }
            }
            if (sign == true) {
              break;
            }
          }
        }
        //使用默认运费
        if (!sign) {
          var beginFee = postageRule.default.begin_postage * 100;
          var addFee = 0;
          if (goodsNum > postageRule.default.begin) {
            addFee = Math.ceil((goodsNum - postageRule.default.begin) / postageRule.default.add) * postageRule.default.add_postage * 100
          }
          return beginFee + addFee;
        }
      }
    } else {
      alert('没有邮费设置');
    }
  },
  //重新计算运费
  freshFee: function (setData) {
    setData = setData || {};
    this.data.shippingFreeFeeText = '';
    var shippingFee = this.calculateFreight();
    setData.shippingFreeFeeText = this.data.shippingFreeFeeText;
    setData.shippingFee = this.data.shippingFee = shippingFee;
    setData.shippingFeeText = this.data.shippingFeeText = shippingFee == 0 ? '免邮费' : (shippingFee / 100).toFixed(2) + '元';
    setData.totalAmountText = this.data.totalAmountText = ((this.data.sku.price * this.data.num + this.data.shippingFee) / 100).toFixed(2) + '元';
    this.setData(setData);
  }
};
var addrPickerOption = {
  data: {
    wiiAddrPicker: {
      'addrPickerUrl': '/wxapp_api/api',
      'addrPickerKey': {
        'setDefault': 'self:uc_api:address:setDefault',
        'delAddr': 'self:uc_api:address:del',
        'getAddrList': 'self:uc_api:address:get',
        'addAddr': 'self:uc_api:address:add'
      }
    }
  }
};
utils.assign(pageSetting, addrPicker, addrPickerOption);
Page(pageSetting)